<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2020/12/31
  Time: 10:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css" media="all">
    <style>
        #left{
            width:49%;
            float: left;
        }
        #right{
            width:49%;
            float: right;
        }
    </style>
</head>
<body>
<%--搜索框表单--%>
<div id="left">
    <br>
    <form action=""  id="updBook" class="layui-form" >
        <div class="layui-form-item">
            <label class="layui-form-label">书名</label>
            <div class="layui-input-inline">
                <input type="text" name="bookname"  placeholder="请输入书名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">类型</label>
            <div class="layui-input-inline">
                <select name="typeid"  id="addlx" lay-filter="aihao">
                    <option value="">请选择书籍的类型</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">作者</label>
            <div class="layui-input-inline">
                <input type="text" name="author"  placeholder="请输入作者名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <button type="button" class="layui-btn" lay-submit lay-filter="ssss">搜索</button>
                <button type="reset" class="layui-btn layui-btn-normal layui-btn-ss">重置</button>
            </div>
        </div>
    </form>

    <%--查询页面--%>
    <table class="layui-hide" id="test" lay-filter="test"></table>
</div>

<div id="right">
    <table class="layui-hide" id="test2" lay-filter="test2"></table>
    <form class="layui-form" lay-filter="xq" id="tj" >
        <div class="layui-form-item">
            <label class="layui-form-label">总数量:</label>
            <div class="layui-input-inline">
                <input type="text" name="totalcount" id="totalcount" class="layui-input" value="0" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">总金额:</label>
            <div class="layui-input-inline">
                <input type="text" name="totalprice" id="totalprice" class="layui-input" value="0" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">经手人:</label>
            <div class="layui-input-inline">
                <input type="text" name="jsr" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <button type="button" class="layui-btn" lay-submit lay-filter="tj">提交</button>
            </div>
        </div>
    </form>
</div>

<%--提交入库表头部工具栏--%>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">全部删除</button>
    </div>
</script>

<%--数据表头部工具栏--%>
<script type="text/html" id="toolbarDemo2">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData2">一键生成购货单</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">添加</a>
</script>

<script type="text/html" id="barDemo2">
    <a class="layui-btn layui-btn-xs" lay-event="edit2">删除</a>
</script>

<script src="${pageContext.request.contextPath}/layui/layui.all.js" charset="utf-8"></script>

<script>
    layui.use(['table','layer','form','jquery'], function(){
        var table = layui.table;
        var layer = layui.layer;
        var $ = layui.jquery;
        var form  = layui.form;
        var fazhi = 100;
        function showtable(){
            table.render({
                elem: '#test'
                ,toolbar: '#toolbarDemo2' //开启头部工具栏，并为其绑定左侧模板
                ,url:'${pageContext.request.contextPath}/book/selectBook'
                ,title: '数据表'
                ,cols: [[
                     {field:'bookid', title:'bookid',fixed: 'left',hide:true,unresize: true, sort: true}
                    ,{field:'bookname', title:'书名'}
                    ,{field:'author', title:'作者'}
                    ,{field:'count', title:'数量',hide:true}
                    ,{field:'remark', title:'介绍',  sort: true,hide:true}
                    ,{field:'typeid', title:'类型编号',hide:true}
                    ,{field:'typename', title:'类型',sort: true}
                    ,{field:'publisher', title:'出版社'}
                    ,{field:'price', title:'价格', sort: true,hide:true}
                    ,{fixed: 'right', title:'操作', toolbar: '#barDemo'}
                ]]
                ,even:true
                ,page: true
                ,limit:5
                ,limits:[3,5,10,20,50]
            });
        }
        var tableData = [];
        table.render({
            elem: '#test2'
            ,data: tableData
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,totalRow: true
            ,title: '提交入库表'
            ,cols: [[
                 {field:'bookid', title:'bookid',fixed: 'left',hide:true,unresize: true, sort: true}
                ,{field:'bookname', title:'书名'}
                ,{field:'author', title:'作者'}
                ,{field:'count', title:'数量', edit: 'text'}
                ,{field:'remark', title:'介绍',  sort: true,hide:true}
                ,{field:'typeid', title:'类型编号',hide:true}
                ,{field:'typename', title:'类型',sort: true}
                ,{field:'publisher', title:'出版社'}
                ,{field:'price', title:'价格' , edit: 'text', sort: true}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo2'}
            ]]
            ,even:true
            ,page: true
        });
        //查询所有书籍类型，并填充到下拉框中
        function showselect(){
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath}/type/selectType',
                dataType:'json',//预期的后台数据类型
                success:function (data) {
                    //通过循环遍历查到的所有类型，并填充到类型下拉框中
                    var op="";
                    for (var i=0;i<data.length;i++){
                        op +="<option value='"+data[i].typeid+"'>"+data[i].typename+"</option>";
                    }
                    $("#addlx").append(op);
                    form.render('select');//表单的更新渲染 下拉框
                }
            })
        }

        //页面整个加载完成时执行
        $(function () {
            showtable();
            showselect();
        })

        //提交入库头工具栏事件
        table.on('toolbar(test2)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    layer.confirm('真的全部删除吗？', function (index) {
                        $("#tj")[0].reset();
                        tableData = []
                        table.reload('test2', {
                            data: tableData
                        });
                        layer.close(index);
                    });
                    break;
                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });
        //数据头工具栏事件
        table.on('toolbar(test)', function(obj){
            var data = layui.table.cache["test"];
            switch(obj.event){
                case 'getCheckData2':
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].count<=fazhi){
                            var flag = false;
                            for (var j = 0; j < tableData.length; j++) {
                                if (data[i].bookid === tableData[j].bookid) {
                                    flag = true;
                                    break;
                                }
                            }
                            // 如果存在相同的数据，不能添加
                            if (flag) {
                                layer.msg("已经存在相同的数据，只需要修改表格中的数量即可！！！");
                            }else{
                                data[i].count=Number(fazhi-data[i].count);
                                tableData.push(data[i]);
                            }
                        }
                        table.reload('test2', {
                            data: tableData
                        });
                        MoneyAndCount();
                        /*if (data[i].count<=fazhi){
                            data[i].count=Number(fazhi-data[i].count);
                        }*/
                    }
                    showtable();
                    break;
                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        /*
        * 搜索表单的提交
        * */
        form.on('submit(ssss)', function(data){
            table.reload('test',{
                where:{
                    bookname:data.field.bookname,
                    typeid:data.field.typeid,
                    author:data.field.author
                },page: {
                    curr:1
                }
            })
        });

        //提交表格入库
        form.on('submit(tj)',function (data){
            $.ajax({
                url: '${pageContext.request.contextPath}/ruku/addruku',
                type: 'post',
                async: false,
                data: {data: JSON.stringify(data.field), tableData: JSON.stringify(tableData)},
                dataType: 'json',
                success: function (data) {
                    if (data == "1001"){
                        $("#tj")[0].reset();
                        tableData = []
                        table.reload('test2', {
                            data: tableData
                        });
                        layer.msg("提交成功",{icon:1});
                    }else{
                        layer.msg("提交失败",{icon:5});
                    }
                }
            })
            return false;
        });

        //添加
        table.on('tool(test)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                var flag = false;
                for (var i = 0; i < tableData.length; i++) {
                    if (data.bookid === tableData[i].bookid) {
                        flag = true;
                        break;
                    }
                }
                // 如果存在相同的数据，不能添加
                if (flag) {
                    layer.msg("已经存在相同的数据，只需要修改表格中的数量即可！！！");
                } else {
                    if (data.count<=fazhi){
                        layer.msg("该书库存低于"+fazhi+"本，建议添加数量不少于"+(fazhi-data.count)+"本！");
                    }
                    // 将表格1的数据添加到tableData中
                    tableData.push(data);
                    // 重新加载表格
                    table.reload('test2', {
                        data: tableData
                    });
                    MoneyAndCount()
                }
                return false;
            }
        });

        //删除
        table.on('tool(test2)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit2') {
                layer.confirm('真的删除行吗？', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    var colIndex = $(obj.tr).attr("data-index");
                    tableData.splice(colIndex, 1);
                    table.reload('test2', {
                        data: tableData
                    });
                    MoneyAndCount()
                    layer.close(index);
                });
            }
        });

        //单元格编辑
        table.on('edit(test2)', function (obj) {
            var data = obj.data;
            var oldText = $(this).prev().text();  // 单元格编辑之前的值
            var checkCount = /^[1-9]*[1-9][0-9]*$/;
            var checkPrice = /^\d+(\.\d+)?$/;
            if (!checkCount.test(data.count)) {
                $(this).val(oldText)
                layer.msg("数量只能是正整数！！！")
            }else if(!checkPrice.test(data.price)) {
                $(this).val(oldText)
                layer.msg("价格只能是正数！！！")
            }else {
                var colIndex = $(obj.tr).attr("data-index");
                tableData[colIndex].count = data.count;
                tableData[colIndex].price = data.price;
                MoneyAndCount()
            }
        })

        //总价和总数量
        function MoneyAndCount() {
            let totalprice = 0;
            let totalcount = 0;
            for (var i = 0; i < tableData.length; i++) {
                totalprice += Number(tableData[i].price) * Number(tableData[i].count);
                totalcount += Number(tableData[i].count);
            }
            $("#totalprice").val(totalprice);
            $("#totalcount").val(totalcount);
        }

    });
</script>

</body>
</html>


